package org.longteng.mobileluck.api;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.longteng.core.base.CommonResult;
import org.longteng.core.utils.ImageUtil;
import org.longteng.mobileluck.algorithm.bean.MobileNumAuspiciousVo;
import org.longteng.mobileluck.algorithm.bean.MobileNumOrcLuckVo;
import org.longteng.mobileluck.algorithm.service.MobileNumAuspiciousService;
import org.longteng.mobileluck.algorithm.service.SelectMobileNumImgLuckService;
import org.longteng.mobileluck.mapstruct.MobileLuckMapper;
import org.longteng.mobileluck.orc.vo.OrcMobileNumResult;
import org.longteng.mobileluck.util.BASE64DecodedMultipartFileUtil;
import org.longteng.mobileluck.vo.MobileLuckVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 手机号测算吉祥接口层
 * @author hymn.com
 */
@RestController
@Slf4j
@Validated
@RequestMapping("api")
public class MobileLuckController {

    @Autowired
    private MobileNumAuspiciousService mobileNumAuspiciousService;
    @Autowired
    private SelectMobileNumImgLuckService selectMobileNumImgLuckService;


    /**
     * 手机号测算吉祥
     * @param mobileMap
     * @return
     */
    @GetMapping("/mobileluck")
    public CommonResult<MobileLuckVo> mobileLuck(@RequestParam Map<String, String> mobileMap)  {
        if (log.isDebugEnabled()) {
            log.debug("手机号测算吉祥参数。{}", mobileMap);
        }

        if (mobileMap == null) {
            return CommonResult.failed("请传入正确参数：?mobile=139********[&wd=姓名&sex=姓名(1,0)&birthday=农历生日&hour=时辰]。");
        }
        String mobile = mobileMap.get("mobile");
        String name = mobileMap.get("wd");
        String sex = mobileMap.get("sex");
        String birthday = mobileMap.get("birthday");
        String hour = mobileMap.get("hour");

        if (StringUtils.isBlank(mobile)) {
            return CommonResult.failed("请传入正确参数mobile。");
        }

        MobileNumAuspiciousVo mobileNumAuspiciousVo = mobileNumAuspiciousService.parseMobileNumLuck(mobile);
        MobileLuckVo mobileLuckVo = MobileLuckMapper.INSTANCT.conver(mobileNumAuspiciousVo);
        if(log.isDebugEnabled()) {
            log.debug("手机号测试吉祥接口结果：{}",mobileLuckVo);
        }
        return CommonResult.success(mobileLuckVo);
    }

    /**
     * 手机号测算吉祥Post
     * @param mobileMap
     * @param mobilePostMap
     * @return
     */
    @PostMapping("/mobileluck")
    public CommonResult<MobileLuckVo> mobileLuckPost(@RequestParam Map<String, String> mobileMap
            , @RequestBody Map<String, String> mobilePostMap)  {
        if (mobileMap == null || mobileMap.isEmpty() ) {
            if (log.isDebugEnabled()) {
                log.debug("手机号测算吉祥,为post参数。");
            }
            mobileMap = mobilePostMap;
        }

        return this.mobileLuck(mobileMap);
    }

    /**
     * 上传选号界面手机号批量测算吉祥
     * @param mobilesImgUpload  选号界面图片
     * @return
     */
    @PostMapping("/mobilesimgluck")
    public CommonResult<List<MobileLuckVo>> selMobilesImgUpload(@RequestParam("imgFile") MultipartFile mobilesImgUpload){
        // 获取文件名
        String fileName = mobilesImgUpload.getOriginalFilename();
        if (log.isDebugEnabled()) {
            log.debug("上传选号界面手机号批量测算吉祥. 上传的图片文件：{}", fileName);
        }
        List<MobileLuckVo> mobileLuckList = new ArrayList<>();
        int orcApiOutErr = 0;

        try {
            byte[] imageBytes = mobilesImgUpload.getBytes();
            MobileNumOrcLuckVo mobileNumOrcLuckVo = selectMobileNumImgLuckService.parseMobileImgNumsLuck(imageBytes);
            orcApiOutErr = mobileNumOrcLuckVo.getBaiduOrcApiCountStatus();
            List<MobileNumAuspiciousVo> mobileNumAuspiciousVoList = mobileNumOrcLuckVo.getMobileNumAuspiciousVoList();
            if (mobileNumAuspiciousVoList != null) {
               for (MobileNumAuspiciousVo mobileNumAuspiciousVo : mobileNumAuspiciousVoList) {
                   MobileLuckVo mobileLuckVo = MobileLuckMapper.INSTANCT.conver(mobileNumAuspiciousVo);
                   mobileLuckList.add(mobileLuckVo);
                   if(log.isDebugEnabled()) {
                       log.debug("选号界面手机号测试吉祥接口结果：{}",mobileLuckVo);
                   }
               }
            }
        } catch (IOException e) {
            log.error("取上传的选号界面图片数据错误.", e);
            return CommonResult.failed("选号界面数据解析错误.");
        }

        if(orcApiOutErr >= 2) {
            return CommonResult.failed(501,"来晚了，ORC图片识别手机号功能已其他人先用光了.");
        }

        return CommonResult.success(mobileLuckList);

    }

    /**
     * 上传选号界面Base64手机号批量测算吉祥
     * @param mobilesImgBase64  选号界面图片Base64
     * @return
     */
    @PostMapping("/mobilesimg2luck")
    public CommonResult<List<MobileLuckVo>> selMobilesImgBase64Upload(@RequestParam("imgBase64") String mobilesImgBase64){
        if(StringUtils.isNotBlank(mobilesImgBase64)) {
            MultipartFile mobilesImgUploadF = BASE64DecodedMultipartFileUtil.base64ToMultipart(mobilesImgBase64);
            return this.selMobilesImgUpload(mobilesImgUploadF);
        } else {
            log.warn("上传选号界面Base64手机号批量测算吉祥,图片内容为空。");
            return CommonResult.failed("图片内容为空");
        }
    }

    /**
     * 取得例子选号图返回页面显示
     * @param lastMap
     * @return
     */
    @PostMapping("/getimg4sample")
    public CommonResult<String> getSampleImgBase64(@RequestParam Map<String, String> lastMap){
        String imgResourcePathName = "static/img/select_mobile_sample.png";
        String mobilesImgBase64 = ImageUtil.imgResourceToBase64(imgResourcePathName);
        if(StringUtils.isBlank(mobilesImgBase64)) {
            log.warn("取得例子选号图内容为空。");
            return CommonResult.failed("图片内容为空");
        }
        /*if(log.isDebugEnabled()) {
            log.debug("取得例子选号图内容:{}", mobilesImgBase64);
        }*/
        return CommonResult.success(mobilesImgBase64);
    }

}
